package com.sunxueqi.framework.security.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.sunxueqi.common.util.SecurityUtils;
import com.sunxueqi.framework.security.LoginUser;
import com.sunxueqi.framework.security.service.TokenService;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 验证token的有效性
 * @author Sun
 *
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter{

	@Autowired
    private TokenService tokenService;
	
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		// 获取用户信息
		LoginUser loginUser = tokenService.getLoginUser(request);
		log.info("The current request URL : {}", request.getRequestURL());
		
		if(ObjectUtil.isNotNull(loginUser) && ObjectUtil.isNotNull(SecurityUtils.getAuthentication())) {
			tokenService.verifyToken(loginUser);
			UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
			// authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
			SecurityContextHolder.getContext().setAuthentication(authenticationToken);
		}
		
		filterChain.doFilter(request, response);
	}
	
	
}
